define(['jquery', 'jquery-weui', 'weui', 'common'], function ($, JqueryWuei, Weui) {
    var Controller = {
        index: function () {
            //上传按钮事件
            // Controller.api.upload();
            $(".datetime-picker").calendar();
            $('#formSubmitBtn').click(function () {
                Weui.form.validate('#form1', function (error) {
                    console.log(error);
                    if (!error) {
                        setbutton(0);
                        $.ajax({
                            //几个参数需要注意一下
                            type: "POST",//方法类型
                            dataType: "json",//预期服务器返回的数据类型
                            url: "/index.php/index/schoolfriend",//url
                            data: $('#form1').serialize(),
                            success: function (ret) {
                                if (ret.code == 1) {
                                    $.alert({
                                        title: ret.msg,
                                        text: ret.data.nickname + '&nbsp;&nbsp;校友您好,预约信息已提交,<br/>待学院审核通过后可扫码入校。',
                                        onOK: function () {
                                            window.location.href = "";
                                        }
                                    });
                                } else if (ret.code == 0) {
                                    $.alert({
                                        title: '提示',
                                        text: ret.msg,
                                        onOK: function () {
                                            window.location.href = "";
                                        }
                                    });
                                }
                                // if(ret.code == 1)
                                //
                            },
                            error: function (error) {
                                console.log(error);
                                alert(JSON.stringify(error))
                                $.alert({
                                    title: '提示',
                                    text: '网络异常,请再次提交！',
                                    onOK: function () {
                                        setbutton(1);
                                    }
                                });
                                // alert("异常！");
                            }
                        });
                    }

                }, {
                    regexp: {
                        IDNUM: /(?:^\d{15}$)|(?:^\d{18}$)|^\d{17}[\dXx]$/,

                    }
                });
                return false;
            });

            // 追加
            $(".btn-addsx").click(function(){
                var tongxing1_status = $(".tongxing1").css('display');
                var tongxing2_status = $(".tongxing2").css('display');
                var tongxing3_status = $(".tongxing3").css('display');
                if(tongxing1_status=='none'){
                    $(".tongxing1").css('display','block');
                    $(".sx1").val(1);
                }
                if(tongxing1_status=='block'){
                    $(".tongxing2").css('display','block');
                    $(".sx2").val(1);
                }
                if(tongxing2_status=='block'){
                    $(".tongxing3").css('display','block');
                    $(".sx3").val(1);
                }

                if(tongxing1_status=='block' && tongxing2_status=='block' && tongxing3_status=='block'){
                    $.alert({
                        title: '提示',
                        text: '随行人员最多可添加三人',
                    });
                }
            });

            // 删除
            $(".btn-del").click(function(){
                var tongxing = $(this).attr('del');
                console.log(tongxing);
                console.log('####');
                $("."+tongxing+' #nickname').val('');
                $("."+tongxing+' #tel').val('');
                $("."+tongxing+' #card_id').val('');
                $("."+tongxing+' #text').val('');
                $("."+tongxing+'').css('display','none');

                $("."+tongxing+' .sx').val(0);

            });
        },
        api: {
            upload: function () {
                var allowTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
                // 1024KB，也就是 1MB
                var maxSize = 1024 * 1024;
                // 图片最大宽度
                var maxWidth = 800;
                var maxHeight = 800;
                var pic_config = {
                    width: 700,
                    height: 700,
                    quality: 1
                };
                // 最大上传图片数量
                var maxCount = 1;

                var tmpl = '<li class="weui-uploader__file weui-uploader__file_status" id="#ImgID#" style="background-image:url(#url#)"> <div class="weui-uploader__file-content"></div></li>',
                    $gallery = $("#gallery"),
                    $galleryImg = $("#galleryImg"),
                    $uploaderInput = $("#uploaderInput"),
                    $uploaderFiles = $("#uploaderFiles"),
                    $uploaderInput1 = $("#uploaderInput1"),
                    $uploaderFiles1 = $("#uploaderFiles1"),
                    $uploaderInput2 = $("#uploaderInput2"),
                    $uploaderFiles2 = $("#uploaderFiles2"),

                    $galleryDelete = $(".weui-gallery__opr"),
                    $previewer = $(".previewer");

                var u = navigator.userAgent;
                if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {

                    // $("#uploaderInput").attr('capture', 'camera');
                }
                $uploaderInput.on("change", function (event) {

                    var src, url = window.URL || window.webkitURL || window.mozURL, files = event.target.files;
                    if (files.length === 0) {
                        return;
                    }

                    var fd = new FormData();
                    for (var i = 0, len = files.length; i < len; i++) {
                        console.log(i)
                        var file = files[i];
                        var fileType = file.type;
                        var reader = new FileReader();
                        //     // 如果类型不在允许的类型范围内
                        if (allowTypes.indexOf(file.type) === -1) {
                            $.toast('该类型不允许上传' + fileType, "forbidden");
                            continue;
                        }
                        // if (file.size > maxSize) {
                        //     $.toast("图片太大，不允许上传", "forbidden");
                        //     continue;
                        // }
                        if ($('#uploaderFiles > .weui-uploader__file').length >= maxCount) {
                            $.toast('最多只能上传' + maxCount + '张图片', "forbidden");
                            return;
                        }

                        // if (url) {
                        //     src = url.createObjectURL(file);
                        // } else {
                        //     src = event.target.result;
                        // }
                        //  $uploaderFiles.append($(tmpl.replace('#url#', src)));
                        // // console.log(src);

                        // // var form=document.getElementById("form1");

                        src = url.createObjectURL(file);

                        // reader.onload = function (e) {


                        var img = new Image();
                        (function (i) {
                            Controller.api.compressImage(src, pic_config, function (result) {
                                console.log(result);
                                console.log(i);

                                fd.append("file", result);
                                $.ajax({
                                    url: "/api/common/upload",
                                    type: "POST",
                                    data: fd,
                                    dataType: 'json',
                                    processData: false,  // 告诉jQuery不要去处理发送的数据
                                    contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                                    async: false,
                                    success: function (res) {
                                        console.log(res);

                                        // $.alert(JSON.stringify(res));
                                        // if($("#pic_ids").val()=='')
                                        //     $("#pic_ids").val(res.id);
                                        // else
                                        //     $("#pic_ids").val($("#pic_ids").val()+","+res.id);
                                        $('#healthy_pic_input').val(res.data.url);
                                        var num = $('#uploaderFiles > .weui-uploader__file').length;
                                        console.log(num);
                                        $('.weui-uploader__info').text(num + '/' + maxCount);
                                        var $preview = $('<li class="weui-uploader__file weui-uploader__file_status" id="ImgID" style="position:relative;background-image:url(' + res.data.url + ')"><div class="close-icon"></div><div class="weui-uploader__file-content">0%</div></li>');
                                        $uploaderFiles.append($preview);
                                        // $uploaderFiles.append($(tmpl.replace('#url#', img.src).replace('#ImgID#',res.id)));
                                        // $uploaderFiles.append($(tmpl.replace('#url#', img.src)));
                                        // $preview.attr('id',res.id);
                                        $preview.removeClass('weui-uploader__file_status').find('.weui-uploader__file-content').remove();

                                    }
                                });
                            })
                        })(i)
                    }
                });
                
                $uploaderInput1.on("change", function (event) {

                    var src, url = window.URL || window.webkitURL || window.mozURL, files = event.target.files;
                    if (files.length === 0) {
                        return;
                    }

                    var fd = new FormData();
                    for (var i = 0, len = files.length; i < len; i++) {
                        console.log(i)
                        var file = files[i];
                        var fileType = file.type;
                        var reader = new FileReader();
                        //     // 如果类型不在允许的类型范围内
                        if (allowTypes.indexOf(file.type) === -1) {
                            $.toast('该类型不允许上传' + fileType, "forbidden");
                            continue;
                        }

                        if ($('#uploaderFiles1 > .weui-uploader__file').length >= maxCount) {
                            $.toast('最多只能上传' + maxCount + '张图片', "forbidden");
                            return;
                        }

                        src = url.createObjectURL(file);

                        var img = new Image();
                        (function (i) {
                            Controller.api.compressImage(src, pic_config, function (result) {
                                console.log(result);
                                console.log(i);

                                fd.append("file", result);
                                $.ajax({
                                    url: "/api/common/upload",
                                    type: "POST",
                                    data: fd,
                                    dataType: 'json',
                                    processData: false,  // 告诉jQuery不要去处理发送的数据
                                    contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                                    async: false,
                                    success: function (res) {
                                        console.log(res);

                                        $('#trip_pic_input').val(res.data.url);
                                        var num = $('#uploaderFiles1 > .weui-uploader__file').length;
                                        console.log(num);
                                        $('.weui-uploader__info').text(num + '/' + maxCount);
                                        var $preview = $('<li class="weui-uploader__file weui-uploader__file_status" id="ImgID" style="position:relative;background-image:url(' + res.data.url + ')"><div class="close-icon"></div><div class="weui-uploader__file-content">0%</div></li>');
                                        $uploaderFiles1.append($preview);
                                        // $uploaderFiles.append($(tmpl.replace('#url#', img.src).replace('#ImgID#',res.id)));
                                        // $uploaderFiles.append($(tmpl.replace('#url#', img.src)));
                                        // $preview.attr('id',res.id);
                                        $preview.removeClass('weui-uploader__file_status').find('.weui-uploader__file-content').remove();

                                    }
                                });
                            })
                        })(i)
                    }
                });

                $uploaderInput2.on("change", function (event) {

                    var src, url = window.URL || window.webkitURL || window.mozURL, files = event.target.files;
                    if (files.length === 0) {
                        return;
                    }

                    var fd = new FormData();
                    for (var i = 0, len = files.length; i < len; i++) {
                        console.log(i)
                        var file = files[i];
                        var fileType = file.type;
                        var reader = new FileReader();
                        //     // 如果类型不在允许的类型范围内
                        if (allowTypes.indexOf(file.type) === -1) {
                            $.toast('该类型不允许上传' + fileType, "forbidden");
                            continue;
                        }

                        if ($('#uploaderFiles2 > .weui-uploader__file').length >= maxCount) {
                            $.toast('最多只能上传' + maxCount + '张图片', "forbidden");
                            return;
                        }

                        src = url.createObjectURL(file);

                        var img = new Image();
                        (function (i) {
                            Controller.api.compressImage(src, pic_config, function (result) {
                                console.log(result);
                                console.log(i);

                                fd.append("file", result);
                                $.ajax({
                                    url: "/api/common/upload",
                                    type: "POST",
                                    data: fd,
                                    dataType: 'json',
                                    processData: false,  // 告诉jQuery不要去处理发送的数据
                                    contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                                    async: false,
                                    success: function (res) {
                                        console.log(res);

                                        $('#nuclein_pic_input').val(res.data.url);
                                        var num = $('#uploaderFiles2 > .weui-uploader__file').length;
                                        console.log(num);
                                        $('.weui-uploader__info').text(num + '/' + maxCount);
                                        var $preview = $('<li class="weui-uploader__file weui-uploader__file_status" id="ImgID" style="position:relative;background-image:url(' + res.data.url + ')"><div class="close-icon"></div><div class="weui-uploader__file-content">0%</div></li>');
                                        $uploaderFiles2.append($preview);
                                        // $uploaderFiles.append($(tmpl.replace('#url#', img.src).replace('#ImgID#',res.id)));
                                        // $uploaderFiles.append($(tmpl.replace('#url#', img.src)));
                                        // $preview.attr('id',res.id);
                                        $preview.removeClass('weui-uploader__file_status').find('.weui-uploader__file-content').remove();

                                    }
                                });
                            })
                        })(i)
                    }
                });

                var index;
                $uploaderFiles.on("click", "li", function () {
                    console.log(12312);
                    index = $(this).index();
                    $galleryImg.attr("style", this.getAttribute("style"));
                    $galleryDelete.show();
                    $gallery.fadeIn(100);
                });
                $uploaderFiles1.on("click", "li", function () {
                    console.log(12312);
                    index = $(this).index();
                    $galleryImg.attr("style", this.getAttribute("style"));
                    $galleryDelete.show();
                    $gallery.fadeIn(100);
                });
                $uploaderFiles2.on("click", "li", function () {
                    console.log(12312);
                    index = $(this).index();
                    $galleryImg.attr("style", this.getAttribute("style"));
                    $galleryDelete.show();
                    $gallery.fadeIn(100);
                });

                $('.image-previewer-box').on("click", "li", function () {
                    index = $(this).index();
                    $galleryImg.attr("style", this.getAttribute("style"));
                    $galleryDelete.hide();
                    $gallery.fadeIn(100);
                });
                $('.image-previewer-box').on("click", ".close-icon", function () {
                    $(this).parent('li').remove();
                });

                $gallery.on("click", function () {
                    $gallery.fadeOut(100);
                });


                $(".weui-gallery__del").click(function () {
                    var picid = $uploaderFiles.find("li").eq(index).attr("id");

                    $uploaderFiles.find("li").eq(index).remove();
                    str = $("#pic_ids").val();
                    newstr = (',' + str + ',').replace(',' + picid + ',', ',').substr(1).replace(/,$/, '');
                    $("#pic_ids").val(newstr);

                    // $.ajax({
                    //         url: "deletePic/ids/"+picid,
                    //         dataType : 'json',
                    //         success: function(res){

                    //     }
                    // });

                })
            },
            convertBase64UrlToBlob: function (urlData) {
                console.log(urlData);
                var arr = urlData.split(',')
                var mime = arr[0].match(/:(.*?);/)[1]
                console.log(mime)
                var bstr = atob(arr[1])
                var n = bstr.length
                var u8arr = new Uint8Array(n)
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n)
                }
                return new Blob([u8arr], {type: mime})
            },
            convertBase64UrltoFile: function (dataurl) {
                var filename = 'file'
                var arr = dataurl.split(',')
                var mime = arr[0].match(/:(.*?);/)[1]
                var suffix = mime.split('/')[1]
                var bstr = atob(arr[1])
                var n = bstr.length
                var u8arr = new Uint8Array(n)
                while (n--) {
                    u8arr[n] = bstr.charCodeAt(n)
                }
                return new File([u8arr], filename + '.' + suffix, {
                    type: mime
                })
            },
            compressImage: function (path, config, callback) {

                var img = new Image()
                img.src = path
                img.onload = function () {
                    var that = this
                    var width_ratio = config.width / that.width;
                    var height_ratio = config.height / that.height;
                    if (width_ratio >= height_ratio) {
                        var w = Math.min(config.width, that.width);
                        // 高度按比例计算
                        var h = that.height * (w / that.width);
                    }
                    // 源图过宽
                    else if (width_ratio <= height_ratio) {

                        var h = Math.min(config.height, that.height);
                        var w = that.width * (h / that.height);
                    }
                    var quality = 0.7 // 默认图片质量为0.7
                    // 生成canvas
                    var canvas = document.createElement('canvas')
                    var ctx = canvas.getContext('2d')
                    // 创建属性节点
                    var anw = document.createAttribute('width')
                    anw.nodeValue = w
                    var anh = document.createAttribute('height')
                    anh.nodeValue = h
                    canvas.setAttributeNode(anw)
                    canvas.setAttributeNode(anh)
                    ctx.drawImage(that, 0, 0, w, h)
                    if (config.quality && config.quality <= 1 && config.quality > 0) {
                        quality = config.quality
                    }
                    var base64 = canvas.toDataURL('image/*', quality)
                    var blob = Controller.api.convertBase64UrltoFile(base64)
                    // 回调函数返回blob的值（若不需要，可直接返回base64的值）
                    callback(blob)
                }
            },

        }
    };
    return Controller;
});


